/**
 *
 * @param {string} type
 *
 */
const support = (type) => window && window[type];

window.addEventListener("load", () => {
  const byIntersectionObserver = () => {
    const lazyImages = document.querySelectorAll(".lazy-image");

    const lazyImageCallback = (entries) => {
      entries.forEach((entry) => {
        console.log("🚀 ~ entries.forEach ~ entry:", entry);
        if (entry.isIntersecting) {
          const lazyImage = entry.target;
          const realSrc = lazyImage.dataset.src;
          console.log("🚀 ~ entries.forEach ~ realSrc:", realSrc);
          lazyImage.src = realSrc;
          // 停止观察该图片
          observer.unobserve(lazyImage);
        }
      });
    };
    const observer = new IntersectionObserver(lazyImageCallback, {
      root: null,
      rootMargin: "0px",
      threshold: 0.1,
    });
    lazyImages.forEach((image) => {
      observer.observe(image);
    });
  };
  const byOffsetTop = () => {
    const imgs = document.querySelectorAll(".lazy-image");
    const innerHeight = window.innerHeight;
    const getOffsetTop = (ele, sum = ele?.offsetTop) => {
      if (ele?.parentNode?.tagName?.toLowerCase() === "body") {
        return sum;
      } else if (window.getComputedStyle(ele?.parentNode)?.position) {
        return getOffsetTop(ele?.parentNode, sum + ele?.parentNode?.offsetTop);
      } else {
        return getOffsetTop(ele?.parentNode, sum);
      }
    };
    const onLazy = () => {
      const scrollTop =
        document.body.scrollTop || document.documentElement.scrollTop;
      Array.from(imgs).forEach((img) => {
        const offsetTop = getOffsetTop(img);
        const imgOffsetTop = offsetTop;
        const dataSrc = img.getAttribute("data-src");
        if (imgOffsetTop < scrollTop + innerHeight) {
          img.src = dataSrc;
        }
      });
    };
    onLazy();
    window.onscroll = onLazy;
  };

  if (support("IntersectionObserver")) {
    byIntersectionObserver();
  } else {
    byOffsetTop();
  }
});
